
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;

using JYJ.AiYard.Extension;
using JYJ.AiYard.StationManagement.TbYardLovingLists;
using JYJ.AiYard.StationManagement.TbYardLovingLists.Dtos;
using JYJ.AiYard.StationManagement.TbYardLovingLists.DomainService;
using JYJ.AiYard.StationManagement.TbYardLovingLists.Authorization;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbYardLovingLists
{
    /// <summary>
    /// TbYardLovingList应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYardLovingListAppService : AiYardAppServiceBase, ITbYardLovingListAppService
    {
        private readonly IRepository<TbYardLovingList, long> _entityRepository;

        private readonly ITbYardLovingListManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbYardLovingListAppService(
        IRepository<TbYardLovingList, long> entityRepository
        ,ITbYardLovingListManager entityManager
        , IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
             _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }


        /// <summary>
        /// 获取TbYardLovingList的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbYardLovingListPermissions.Query)] 
        public async Task<PagedResultDto<TbYardLovingListListDto>> GetPaged(GetTbYardLovingListsInput input)
		{
            //// TODO:根据传入的参数添加过滤条件 
            List<long> StationList = new List<long>();
            tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            var query1 = _aiYardDbTableIssuedCard.GetTbYardLovingList(StationList, filterText.FilterText);

            var query = query1.AsQueryable();
            var count = query.Count();

            //var count = await query.CountAsync();

            var entityList = query
                .OrderBy(input.Sorting).AsNoTracking()
                .PageBy(input)
                .ToList();
             
            var entityListDtos =entityList.MapTo<List<TbYardLovingListListDto>>();

			return new PagedResultDto<TbYardLovingListListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TbYardLovingListListDto信息
		/// </summary>
		[AbpAuthorize(TbYardLovingListPermissions.Query)] 
		public async Task<TbYardLovingListListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbYardLovingListListDto>();
		}

		/// <summary>
		/// 获取编辑 TbYardLovingList
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardLovingListPermissions.Create,TbYardLovingListPermissions.Edit)]
		public async Task<GetTbYardLovingListForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbYardLovingListForEditOutput();
            TbYardLovingListEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbYardLovingListEditDto>();
                 
			}
			else
			{
				editDto = new TbYardLovingListEditDto();
			}

			output.TbYardLovingList = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbYardLovingList的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardLovingListPermissions.Create,TbYardLovingListPermissions.Edit)]
		public async Task<Dictionary<string,string>> CreateOrUpdate(CreateOrUpdateTbYardLovingListInput input)
		{
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (input.TbYardLovingList.Station_ID <= 0)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "请选择确定的场所名称!");
                return result; 
            }
            if (!isPlateLicense(input.TbYardLovingList.CardNo))
            {
                result.Add("retype", "-1");
                result.Add("revalue", "非法的车牌号码!");
                return result; 
            }
            if (input.TbYardLovingList.Id.HasValue)
			{
                if (_entityRepository.GetAll().Where(o => o.Station_ID == input.TbYardLovingList.Station_ID
                     && o.CardNo == input.TbYardLovingList.CardNo && o.Id != input.TbYardLovingList.Id).Count() > 0)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "车牌号码不允许重复!");
                    return result; 
                }
                await Update(input.TbYardLovingList);
			}
			else
            {
                if (_entityRepository.GetAll().Where(o => o.Station_ID == input.TbYardLovingList.Station_ID
                 && o.CardNo == input.TbYardLovingList.CardNo).Count() > 0)
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "车牌号码不允许重复!");
                    return result; 
                }
                await Create(input.TbYardLovingList);
			}

            result.Add("retype", "1");
            result.Add("revalue", "保存成功!");
            return result;
        }


		/// <summary>
		/// 新增TbYardLovingList
		/// </summary>
		[AbpAuthorize(TbYardLovingListPermissions.Create)]
		protected virtual async Task<TbYardLovingListEditDto> Create(TbYardLovingListEditDto input)
        {
           
            input.Op_User_NO = AbpSession.GetUserName();
            input.Op_User_Name = AbpSession.GetUserEmail();
            input.Op_Time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            var entity=input.MapTo<TbYardLovingList>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbYardLovingListEditDto>();
		}

		/// <summary>
		/// 编辑TbYardLovingList
		/// </summary>
		[AbpAuthorize(TbYardLovingListPermissions.Edit)]
		protected virtual async Task Update(TbYardLovingListEditDto input)
		{
            
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);
             
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbYardLovingList信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardLovingListPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbYardLovingList的方法
		/// </summary>
		[AbpAuthorize(TbYardLovingListPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}

        #region 判断是否合法车牌号码
        /// <summary>
        /// 判断是否合法车牌号码
        /// </summary>
        /// <param name="PlateNo"></param>
        /// <returns></returns>
        public static bool isPlateLicense(string PlateNo)
        {
            try
            {
                if (PlateNo == "_无_" || PlateNo == "无" || PlateNo.Contains("无"))
                {
                    return true;
                }
                string Value = "粤军警WJ港京津沪冀豫晋鲁桂滇黔川苏浙湘鄂新藏黑皖闽琼辽陕甘青吉蒙渝宁赣贵云甲乙丙丁戊己庚辛壬癸学澳港挂";
                if (PlateNo.Length < 7 || PlateNo.Length > 8)
                {
                    return false;
                }
                for (int i = 0; i < PlateNo.Length; i++)
                {
                    if (PlateNo.Substring(i, 1).ToUpper() == "I"
                        || PlateNo.Substring(i, 1).ToUpper() == "O")
                    {
                        return false;
                    }
                }
                if (!Value.Contains(PlateNo.Substring(0, 1)))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        ///// <summary>
        ///// 导出TbYardLovingList为excel表,等待开发。
        ///// </summary>
        ///// <returns></returns>
        //public async Task<FileDto> GetToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}

    }
}


